const jwt = require('jsonwebtoken')

const {JWT_SECRET} = require('../config/config.default')
const { 
	getUserInfo,
	getAllUsers,
	getUserInfoById,
	modifyUserInfo,
	fuzzyQuery
} = require('../service/user.service')
const { addUser } = require('../service/user.service')


class UserController {
	async register(ctx, next) {
		console.log(ctx.request.body);
		// 1. 获取数据
		const { user_name, password,stuNum,phone} = ctx.request.body
		// console.log(stuNum);
		// 2. 操作数据库
		const res = await addUser({user_name, password, stuNum,phone})

		// 3. 返回结果
		ctx.body = {
			code: 0,
			message: '用户注册成功',
			result: {
				id:res.id,
				user_name:res.user_name,
				stuNum:res.stuNum,
				phone:res.phone
			}
		}
	}
	async login(ctx, next) {
		const { stuNum } = ctx.request.body
		try {
			const { password, ...res } = await getUserInfo({ stuNum })
			ctx.body = {
				code: 0,
				message: '登录成功',
				result: {
					token: jwt.sign(res, JWT_SECRET, { expiresIn: '1d' })
				}
			}
		} catch (err) {
			console.error('用户登录失败', err);
		}
	}

	async getAllUserInfo(ctx,next){
		// try {
			const res = await getAllUsers()
			ctx.body = {
				res
			}
		// }
		// catch (err) {
		// 	console.error('出错');
		// }
	}

	async modifyUser(ctx,next){
		const id = ctx.request.query.id
		const {user_name,stuNum,phone} = ctx.request.body
		try {
			const res = await getUserInfoById(id)
			if(res){
				try {
					await modifyUserInfo({user_name,stuNum,phone},id)
					ctx.body = {
						code:0,
						message:'修改用户信息成功',
						result:{
							id,
							user_name,
							stuNum,
							phone
						}
					}
				} catch (err) {
					console.error('出错');
				}
			}else{
				console.error('id出错');
			}
		} catch (err) {
			console.error('出错');
		}
		
	}

	async searchUsers(ctx,body){
		const keywords = ctx.request.query.keywords
		const id = keywords
		const user_name = keywords
		const stuNum = keywords
		const phone = keywords

		const res = await fuzzyQuery({id,user_name,stuNum,phone})
		ctx.body ={
			res
		}
	}
}
module.exports = new UserController()